﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TextAdornment
{
    /// <summary>
    /// Interaction logic for CodeEditorControl.xaml
    /// </summary>
    public partial class CodeEditorControl : UserControl
    {
        private Window hostWindow;
        private TextAdornment textAdornment;
        private TextAdornmentImage clickedImage;

        public CodeEditorControl(TextAdornmentImage clickedImage, TextAdornment textAdornment)
        {
            InitializeComponent();

            // initialize host window
            hostWindow = new Window();
            hostWindow.SizeToContent = SizeToContent.WidthAndHeight;
            hostWindow.ResizeMode = ResizeMode.NoResize;
            hostWindow.WindowStyle = WindowStyle.None;
            hostWindow.BorderThickness = new Thickness(1, 1, 1, 1);

            // set text adornment
            this.textAdornment = textAdornment;

            // set clicked image
            this.clickedImage = clickedImage;

            // set content to textbox text
            tbxCodeEditor.Text = textAdornment.HtbVariables[clickedImage.InnerText].ToString();
        }

        public void Popup(Point popupPosition)
        {
            hostWindow.Content = this;
            hostWindow.Left = popupPosition.X;
            hostWindow.Top = popupPosition.Y;
            hostWindow.ShowDialog();
        }

        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            if (tbxCodeEditor.Text != textAdornment.HtbVariables[clickedImage.InnerText].ToString())
            {
                // update hashtable
                (textAdornment.HtbVariables[clickedImage.InnerText] as VariationPoint).Content = tbxCodeEditor.Text;

                // update inner text of related images
                foreach (var image in textAdornment.ListImages)
                {
                    if (image.InnerText == clickedImage.InnerText)
                    {
                        (image.ToolTip as ToolTip).Content = textAdornment.HtbVariables[clickedImage.InnerText].ToString();
                    }
                }

                // update spc file
                textAdornment.IOService.UpdateCode(clickedImage.InnerText, textAdornment.HtbVariables[clickedImage.InnerText].ToString());
            }

            // close host window
            hostWindow.Close();
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            hostWindow.Close();
        }
    }
}
